<?php

namespace app\utils\script;

/**
 * POST请求接口JS代码，将整个 vue app 序列化JSON提交
 */
class PostScript implements JSScript{
    private $txt = '';
    private $arg = '';
    /**
     * @param mixed $success_info 支持传递 JSFileScript,string，JSFILE为代码片段
     * @param mixed $err_info 支持传递 JSFileScript,string，JSFILE为代码片段
     */
    public function __construct($method,$url,$success_info='请求成功',$err_info='请求失败',$arg='event')
    {
        $this->arg= $arg;
        if($success_info instanceof JSScript){
            $success_info=$success_info->text();
        }else{
            $success_info='alert(`'.$success_info.'`)';
        }
        if($err_info instanceof JSScript){
            $err_info=$err_info->text();
        }else{
            $err_info='alert(`'.$err_info.'`)';
        }
        $this->txt='
            let xhr = new XMLHttpRequest();
            xhr.open("'.$method.'","'.$url.'");
            xhr.addEventListener("loadend",function(ev){
                if(xhr.readyState==4 && xhr.status==200){
                    '.$success_info.'
                }else{
                    if(xhr.readyState==4){
                        '.$err_info.'
                    }
                }
            })
            xhr.setRequestHeader("content-type","application/json")
            xhr.send(JSON.stringify(current_app))
        ';
    }
    public function text(){
        return $this->txt;
    }
    public function argv(){
        return '('.$this->arg.')';
    }
}